import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/components/diolog/dialog.dart';
import 'package:pornhub_app/views/community/post_publish/publish_rules.dart';
import 'package:pornhub_app/views/community/publish_video/post_publish_page_controller.dart';

class PostPublishVideoPage extends GetView<PostPublishVideoPageController> {
  const PostPublishVideoPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(PostPublishVideoPageController());

    return KeyboardDismissOnTap(
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: _buildAppBar(),
        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildContentInput(),
                        const SizedBox(height: 20),
                        _buildTypeSelectionHeader(),
                        const SizedBox(height: 10),
                        _buildTypeSelection(),
                        const SizedBox(height: 26),
                        _buildVideoSelectionHeader(),
                        const SizedBox(height: 10),
                        _buildVideoSelection(),
                        if (controller.isUploading.value)
                          _buildUploadProgress(),
                      ],
                    ),
                  ),
                ),
              ),
              _buildBottomPublishArea(),
              const SizedBox(height: 10),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUploadProgress() {
    return Obx(() => Container(
      margin: const EdgeInsets.only(top: 16),
      child: Column(
        children: [
          LinearProgressIndicator(
            value: double.parse(controller.uploadProgress.value) / 100,
            backgroundColor: Colors.grey[700],
            valueColor: const AlwaysStoppedAnimation<Color>(Color(0xffff9000)),
          ),
          const SizedBox(height: 8),
          Text(
            "上传进度: ${controller.uploadProgress.value}%",
            style: const TextStyle(
              color: Colors.white,
              fontSize: 14,
            ),
          ),
        ],
      ),
    ));
  }

  Widget _buildVideoSelectionHeader() {
    return Row(
      children: [
        const Text(
          "选择视频",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
        Opacity(
          opacity: 0.6,
          child: Padding(
            padding: const EdgeInsets.only(top: 3),
            child: Text(
              "  (选择1个视频)",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildVideoSelection() {
    return Obx(() {
      if (controller.videoFile.value == null) {
        return _buildAddVideoButton();
      } else {
        return _buildVideoPreview();
      }
    });
  }

  Widget _buildAddVideoButton() {
    return GestureDetector(
      onTap: () => controller.pickVideo(),
      child: Container(
        height: 200,
        decoration: BoxDecoration(
          color: const Color(0xff272727),
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.video_library,
                color: Color(0xffa4a4a4),
                size: 40,
              ),
              SizedBox(height: 8),
              Text(
                "选择视频",
                style: TextStyle(
                  color: Color(0xffa4a4a4),
                  fontSize: 14,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

// 格式化时长
  String _formatDuration(int seconds) {
    final duration = Duration(seconds: seconds);
    String twoDigits(int n) => n.toString().padLeft(2, "0");
    String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
    String twoDigitSeconds = twoDigits(duration.inSeconds.remainder(60));
    return "${twoDigits(duration.inHours)}:$twoDigitMinutes:$twoDigitSeconds";
  }

// 格式化文件大小
  String _formatFileSize(int bytes) {
    if (bytes <= 0) return "0 B";
    const suffixes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    var i = (log(bytes) / log(1024)).floor();
    return '${(bytes / pow(1024, i)).toStringAsFixed(2)} ${suffixes[i]}';
  }


  Widget _buildVideoPreview() {
    return Container(
      height: 200,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
      ),
      child: Stack(
        children: [
          // 视频封面
          if (controller.videoCover.value != null)
            Container(
              width: double.infinity,
              height: double.infinity,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8),
                image: DecorationImage(
                  image: FileImage(controller.videoCover.value!),
                  fit: BoxFit.cover,
                ),
              ),
            ),

          // 视频信息
          Positioned(
            bottom: 8,
            left: 8,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.6),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                "${controller.videoInfo.value['duration'] ?? 0}秒",
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 12,
                ),
              ),
            ),
          ),

          // 播放图标
          Center(
            child: Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.6),
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.play_arrow,
                color: Colors.white,
                size: 32,
              ),
            ),
          ),

          // 删除按钮
          Positioned(
            right: 8,
            top: 8,
            child: GestureDetector(
              onTap: () => controller.removeVideo(),
              child: Container(
                padding: const EdgeInsets.all(4),
                decoration: const BoxDecoration(
                  color: Colors.black54,
                  shape: BoxShape.circle,
                ),
                child: const Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 20,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      backgroundColor: Colors.black,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.white),
        onPressed: () => Get.back(),
      ),
      title: const Text(
        "发布视频",
        style: TextStyle(
          color: Colors.white,
          fontWeight: FontWeight.w500,
          fontSize: 18.0,
        ),
      ),
    );
  }

  Widget _buildContentInput() {
    return TextField(
      controller: controller.textController,
      style: const TextStyle(color: Colors.white),
      maxLines: 8,
      cursorColor: Colors.white,
      decoration: InputDecoration(
        hintText: '请输入视频描述...',
        hintStyle: TextStyle(
          color: Colors.white.withOpacity(0.6),
          fontWeight: FontWeight.w600,
          fontSize: 16.0,
        ),
        border: InputBorder.none,
      ),
    );
  }

  Widget _buildTypeSelectionHeader() {
    return Row(
      children: [
        const Text(
          "选择发布类型",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
        Opacity(
          opacity: 0.6,
          child: Padding(
            padding: const EdgeInsets.only(top: 2),
            child: Text(
              " (必填)",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w600,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildTypeSelection() {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Obx(() {
        return Row(
          children: controller.publishTagsList.map((tag) {
            return Padding(
              padding: const EdgeInsets.only(right: 10),
              child: _buildTypeButton(tag.name),
            );
          }).toList(),
        );
      }),
    );
  }

  Widget _buildTypeButton(String type) {
    return Obx(() {
      final isSelected = controller.isTypeSelected(type);
      return GestureDetector(
        onTap: () => controller.toggleType(type),
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? const Color(0xffff9000) : const Color(0xff272727),
            borderRadius: BorderRadius.circular(20),
            border: isSelected
                ? Border.all(color: const Color(0xffff9000), width: 2)
                : null,
          ),
          child: Text(
            type,
            style: TextStyle(
              color: isSelected ? Colors.black : Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      );
    });
  }

  Widget _buildBottomPublishArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: const BoxDecoration(
        color: Colors.black,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildAgreementRow(),
          const SizedBox(height: 20),
          _buildPublishButton(),
        ],
      ),
    );
  }

  Widget _buildAgreementRow() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Obx(() => GestureDetector(
          onTap: controller.toggleAgreement,
          child: Icon(
            controller.isAgreedToRules.value
                ? Icons.check_circle
                : Icons.radio_button_unchecked,
            color: controller.isAgreedToRules.value
                ? const Color(0xffff9000)
                : Colors.grey,
            size: 20,
          ),
        )),
        const SizedBox(width: 8),
        const Text(
          "请阅读并遵守",
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.w400,
            fontSize: 12.0,
          ),
        ),
        GestureDetector(
          onTap: () {
            Get.to(PublishRulesPage(), opaque: false);
          },
          child: const Padding(
            padding: EdgeInsets.only(left: 3),
            child: Text(
              "《发布规则》",
              style: TextStyle(
                color: Color(0xffff9000),
                fontWeight: FontWeight.w400,
                fontSize: 12.0,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPublishButton() {
    return Obx(() => GestureDetector(
      onTap: () {
        if (!controller.isAgreedToRules.value) {
          showToast("请先阅读并同意发布规则");
          return;
        }
        if (controller.isLoading.value) return;
        if (controller.videoFile.value == null) {
          showToast("请选择要发布的视频");
          return;
        }
        if (controller.uploadedVideoInfo == null && !controller.isUploading.value) {
          showToast("请等待视频上传完成");
          return;
        }

        controller.publishVideo();
      },
      child: Container(
        width: ScreenUtil().screenWidth,
        height: 42,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(21)),
          color: controller.isLoading.value || controller.isUploading.value
              ? Colors.grey
              : const Color(0xffff9000),
        ),
        child: controller.isLoading.value
            ? const SizedBox(
          width: 20,
          height: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation<Color>(Colors.black),
          ),
        )
            : const Text(
          "发布",
          style: TextStyle(
            color: Color(0xff000000),
            fontWeight: FontWeight.w600,
            fontSize: 16.0,
          ),
        ),
      ),
    ));
  }
}
